<template>
  <div>
    <el-main>
      <el-button type="primary" plain icon="el-icon-plus" @click="BeforeAdd()"
        >添加商品</el-button
      >
      <el-table :data="tableData">
        <el-table-column fixed prop="id" label="ID" width="140">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="120">
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120">
        </el-table-column>
        <el-table-column prop="image" label="图片" width="120">
          <template slot-scope="scope">
            <el-image
              style="width: 102.4px; height: 76.8px"
              :src="scope.row.image"
              :preview-src-list="scope.row.srcList"
            >
            </el-image>
          </template>
        </el-table-column>
        <!-- 绿:#67C23A 红:#F56C6C 黄:#E6A23C 蓝:#409EFF 灰:#909399-->
        <el-table-column prop="status" label="状态"
          ><template slot-scope="scope">
            <span v-if="scope.row.status === 0" style="color: #409eff"
              >待上架</span
            >
            <span v-if="scope.row.status === 1" style="color: #67c23a"
              >已上架</span
            >
            <span v-if="scope.row.status === 2" style="color: #909399"
              >已下架</span
            >
            <span v-if="scope.row.status === 3" style="color: #f56c6c"
              >已删除</span
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <!-- 0:待上架;1:已上架;2:已下架;3:已删除 -->
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0"
              ><el-button
                type="success"
                icon="el-icon-upload2"
                plain
                @click="handleGoodsStatusChange(scope.row, 1)"
                size="small"
                >上架</el-button
              ><el-button
                type="primary"
                icon="el-icon-edit"
                plain
                @click="BeforeEdit(scope.row)"
                size="small"
                >编辑</el-button
              >
            </span>
            <span v-if="scope.row.status === 1"
              ><el-button
                @click="handleGoodsStatusChange(scope.row, 2)"
                type="warning"
                icon="el-icon-download"
                size="small"
                plain
                >下架</el-button
              >
            </span>
            <span v-if="scope.row.status === 2"
              ><el-button
                @click="handleGoodsStatusChange(scope.row, 1)"
                type="success"
                icon="el-icon-upload2"
                size="small"
                plain
                >上架</el-button
              >
              <el-button
                @click="handleGoodsStatusChange(scope.row, 3)"
                type="danger"
                icon="el-icon-delete"
                size="small"
                plain
                >删除</el-button
              >
            </span>
            <span v-if="scope.row.status === 3"
              ><el-button
                @click="handleGoodsStatusChange(scope.row, 0)"
                type="primary"
                icon="el-icon-back"
                size="small"
                plain
                >找回</el-button
              >
              <el-button
                @click="completeDel(scope.row)"
                type="danger"
                icon="el-icon-delete"
                size="small"
                plain
                >完全删除</el-button
              >
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- pagination -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-sizes="[5, 10, 20]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- addForm -->
    <el-dialog title="新增" :visible.sync="addFormVisible">
      <el-form :model="ruleForm">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-select v-model="ruleForm.cid" filterable placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.price" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- editForm -->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="ruleForm">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-select v-model="ruleForm.cid" filterable placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            ref="upload"
            action="#"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="ruleForm.images"
            :auto-upload="false"
            list-type="picture-card"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="submitUpload"
                >上传到服务器</el-button
              >
            </div>
          </el-upload>

          <!-- <img :src="ruleForm.image[0].url" /> -->
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="ruleForm.status" placeholder="请选择状态">
            <el-option label="待上架" value="0"></el-option>
            <el-option label="已上架" value="1"></el-option>
            <el-option label="已下架" value="2"></el-option>
            <el-option label="已删除" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="ruleForm.introduction"
          ></el-input>
        </el-form-item>
        <el-form-item label="详情" :label-width="formLabelWidth">
          <tinymce v-model="ruleForm.description" :height="200" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-button type="primary" @click="addAdds()">新增附加信息</el-button>
        </el-form-item>
        <el-form-item
          v-for="(adds, index) in ruleForm.additions"
          :label="'附加' + index"
          :key="adds.index"
          :label-width="formLabelWidth"
        >
          <el-row :gutter="20">
            <el-col :span="2"><el-tag>附加名: </el-tag></el-col>
            <el-col :span="8">
              <el-input
                placeholder="标签名"
                v-model="adds.name"
                label="标签名"
              ></el-input>
            </el-col>
            <el-col :span="2"><el-tag>附加值: </el-tag></el-col>
            <el-col :span="8">
              <el-input
                v-model="adds.value"
                placeholder="标签值"
                label="标签值"
              >
              </el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="danger" @click.prevent="removeAdds(adds)"
                >删除</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imageFormVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { add, list, edit, upload, del, changeStatus } from "@/api/goods";
import Tinymce from "@/components/Tinymce";
import { listCategory } from "@/api/category";

export default {
  name: "Goods",
  components: { Tinymce },
  data() {
    return {
      loadding: false,
      addFormVisible: false,
      editFormVisible: false,
      imageFormVisible: false,
      dialogImageUrl: "",
      formLabelWidth: "120px",
      fileList: [],
      ruleForm: {
        id: "",
        cid: "",
        name: "",
        price: "",
        image: "",
        images: [{ name: "", url: "" }],
        srcList: [],
        status: "",
        introduction: "",
        description: "",
        categoryName: "",
        additions: [{ name: "", value: "" }],
      },
      newAddText: "",
      nextTodoId: 0,
      tableData: null,
      current: 1,
      size: 5,
      total: null,
      categories: [],
    };
  },
  mounted() {
    this.handleCurrentChange(1);
    this.handleCategroys();
  },
  methods: {
    // 获取分类信息
    handleCategroys() {
      listCategory().then((res) => {
        this.categories = res;
        console.log(this.categories);
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      list(this.current, val)
        .then((res) => {
          console.log(res);
          this.tableData = res.records;
          this.total = res.total;
          this.current = res.current;
          this.size = res.size;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      list(val, this.size).then((res) => {
        console.log(res);
        this.tableData = res.records;
        this.total = res.total;
        this.current = res.current;
        this.size = res.size;
      });
    },
    BeforeAdd() {
      this.addFormVisible = true;
      this.ruleForm.name = null;
      this.ruleForm.cid = 1;
      this.ruleForm.price = 6;
    },
    handleAdd() {
      this.addFormVisible = false;
      console.log("add");
      add(this.ruleForm).then((res) => {
        console.log(res);
        this.$message("添加成功");
        this.addFormVisible = false;
        this.handleCurrentChange(this.current);
      });
    },
    BeforeEdit(val) {
      console.log(val.name);
      this.ruleForm = val;
      console.log(this.ruleForm);
      // 提交之前对数据进行处理(图片,分类)
      this.editFormVisible = true;
    },
    handleEdit() {
      this.editFormVisible = false;
 
      this.ruleForm.images = this.$refs.upload.uploadFiles;
      // if (this.ruleForm.images != undefined && this.ruleForm.images.length > 0) {
      //   this.ruleForm.image = this.ruleForm.images[0].url;
      // }
      this.ruleForm.images.forEach((element) => {
        this.fileList.push(element.raw);
      });
      console.log(this.ruleForm);
      edit(this.ruleForm, this.fileList).then((res) => {
        console.log(res);
        this.$message("修改完成");
        this.editFormVisible = false;
        this.handleCurrentChange(this.current);
      });
      this.fileList = [];
    },
    addAdds() {
      this.ruleForm.additions.push({
        value: "",
        name: "",
      });
    },
    removeAdds(item) {
      var index = this.ruleForm.additions.indexOf(item);
      if (index !== -1) {
        this.ruleForm.additions.splice(index, 1);
      }
    },
    // 改变商品状态
    handleGoodsStatusChange(val, m) {
      this.ruleForm = val;
      this.ruleForm.status = m;
      changeStatus(this.ruleForm).then((res) => {
        console.log(res);
        this.$message("修改完成");
        this.editFormVisible = false;
        this.handleCurrentChange(this.current);
      });
    },
    // 完全删除
    completeDel(val) {
      this.ruleForm = val;
      del(this.ruleForm).then((res) => {
        console.log(res);
        this.$message("删除完成");
        this.editFormVisible = false;
        this.handleCurrentChange(this.current);
      });
    },
    // 文件上传
    submitUpload() {
      this.$refs.upload.$refs["upload-inner"].fileList.forEach((element) => {
        this.fileList.push(element.raw);
      });
      console.log(this.fileList);
      upload(this.fileList).then((res) => {
        console.log("返回的列表", res);
        this.$message("上传完成");
        this.ruleForm.images = res;
        this.ruleForm.image = this.ruleForm.images[0].url;
        console.log(this.ruleForm.image);
        this.fileList = [];
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imageFormVisible = true;
    },
  },
};
</script>